﻿using AutoMapper;
using B.S.Business.Domain;
using B.S.Business.ErrorCode;
using B.S.Business.Infacetrue;
using B.S.Business.Write.API.Applications.Command;
using MediatR;
using Yitter.IdGenerator;

namespace B.S.Business.Write.API.Applications.CommandHandler
{
    public class PurchaseAddCommandHandler : IRequestHandler<PurchaseAddCommand, ApiResult<object>>
    {
        private readonly IBaseRepository<Purchase> purchaseRepo;
        private readonly IMapper mapper;

        public PurchaseAddCommandHandler(IBaseRepository<Purchase> purchaseRepo,IMapper mapper)
        {
            this.purchaseRepo = purchaseRepo;
            this.mapper = mapper;
        }
        public Task<ApiResult<object>> Handle(PurchaseAddCommand request, CancellationToken cancellationToken)
        {
            ApiResult<object>result = new ApiResult<object>();

            result.Msg = ApiCode.添加成功.ToString();
            result.Code = ApiCode.添加成功;

            var entity = mapper.Map<Purchase>(request);

            entity.Productcode = YitIdHelper.NextId().ToString();

            entity.IsDeleted = false;

            purchaseRepo.Add(entity);

            result.Data = entity;

            return Task.FromResult(result);
        }
    }
}
